import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Info: 1+10000000 ForkJoinPool
 * @Author: 唐小尊
 * @Date: 2020/3/2  14:34
 */
public class SumTask extends RecursiveTask<Long> {
    //for循环相加最大操作单位，如果end-start>125000则分子任务
    private static final int THRESHOLD = 125000;
    //存放1~10000000的值，其实没必要，但是由于大多数的forkjoin操作都是数组操作，所以就加上数组
    private long[] arr;
    //数组遍历的开始下标
    private int start;
    //数组遍历的结束位置+1
    private int end;

    /**
     * 用于分配子任务的构造函数
     *
     * @param arr
     * @param start
     * @param end
     */
    public SumTask(long[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    /**
     * 子任务求结果
     *
     * @return 单个子任务的结果
     */
    private long subtotal() {
        long sum = 0;
        for (int i = start + 1; i <= end; i++) {
            sum += i;
        }
        return sum;
    }

    /**
     * 类似于递归执行的递归函数，但是方法的执行由ForkJoinPool类来操控
     * 框架操控：分子任务、求结果
     *
     * @return 最终结果
     */
    @Override
    protected Long compute() {
        if ((end - start) <= THRESHOLD) {
            return subtotal();
        } else {
            int middle = (start + end) / 2;
            SumTask left = new SumTask(arr, start, middle);
            SumTask right = new SumTask(arr, middle, end);
            left.fork();
            right.fork();
            //fork()  +  join()  ==  invoke()
            return left.join() + right.join();
        }
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        long[] arr = new long[10000000];
        for (int i = 0; i < 10000000; i++) {
            arr[i] = i + 1;
        }

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> result = pool.submit(new SumTask(arr, 0, arr.length));
        System.out.println("最终计算结果: " + result.invoke() + "耗时：" + (System.currentTimeMillis() - time) + " 毫秒");
        pool.shutdown();
    }
}
